package cn.buk.qms.web;

import cn.buk.api.wechat.entity.WeixinEntConfig;
import cn.buk.api.wechat.entity.WeixinServiceConfig;
import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.qms.BillUtil;
import cn.buk.tms.dto.*;
import cn.buk.tms.entity.config.EnterpriseConfig;
import cn.buk.tms.entity.config.EtermEntConfig;
import cn.buk.tms.sc.SearchCustomerCriteria;
import cn.buk.tms.sc.SearchUserCriteria;
import cn.buk.qms.service.EnterpriseService;
import cn.buk.qms.service.UserService;
import cn.buk.qms.util.ExcelUtils;
import cn.buk.tms.admin.EntAlipayCfgDto;
import cn.buk.tms.common.dto.MarkupConfigDto;
import cn.buk.tms.dto.CustomerDetailDto;
import cn.buk.tms.dto.PassengerDto;
import cn.buk.common.util.DateUtil;
import cn.buk.common.util.VerifyCodeUtil;
import cn.buk.tms.entity.misc.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;


/**
 * @author yfdai
 * @date 2017-01-07
 */
@RestController
@RequestMapping("/admin")
public class AdminController extends BaseController {

  @Autowired
  public AdminController(EnterpriseService enterpriseService,
                         UserService userService) {
    this.enterpriseService = enterpriseService;
    this.userService = userService;

  }

  private final EnterpriseService enterpriseService;

  private final UserService userService;


  @RequestMapping(value = "/users", method = {GET, POST})
  public CommonDto<UserDto> searchUsers(HttpServletRequest request,
                                        @ModelAttribute("sc") SearchUserCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    List<UserDto> users = userService.searchUsers(enterpriseId, sc);

    CommonDto<UserDto> commonDto = new CommonDto<>();
    commonDto.setDataList(users);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  @GetMapping(value = "/user/{id}")
  public UserDto searchUser(HttpServletRequest request,
                            @PathVariable("id") final int id) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.searchUser(enterpriseId, id);
  }

  /**
   * 重置用户密码
   */
  @PostMapping(value = "/user/password")
  public JsonResult resetUserPassword(HttpServletRequest request,
                                      @RequestParam("id") int userId,
                                      @RequestParam("password") String newPassword) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.resetUserPassword(enterpriseId, username, userId, newPassword);
  }

  /**
   * 修改用户的登录用户名
   */
  @PostMapping(value = "/user/username")
  public JsonResult updateUserUsername(HttpServletRequest request,
                                       @RequestParam("id") int userId,
                                       @RequestParam("username") String newUsername) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.updateUserUsername(enterpriseId, username, userId, newUsername);
  }

  /**
   * 修改用户的登录用户名：邮件地址
   */
  @PostMapping(value = "/user/email")
  public JsonResult updateUserEmail(HttpServletRequest request,
                                    @RequestParam("id") int userId,
                                    @RequestParam("email") String email) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.updateUserEmail(enterpriseId, username, userId, email);
  }

  /**
   * 修改用户的登录用户名：手机号
   */
  @PostMapping(value = "/user/mobile")
  public JsonResult updateUserMobile(HttpServletRequest request,
                                     @RequestParam("id") int userId,
                                     @RequestParam("mobile") String mobile) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.updateUserMobile(enterpriseId, username, userId, mobile);
  }


  /**
   * 修改用户的eterm用户名
   */
  @PostMapping(value = "/user/etermUsername")
  public JsonResult updateUserEtermUsername(HttpServletRequest request,
                                            @RequestParam("id") int userId,
                                            @RequestParam("etermUsername") String etermUsername) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.updateUserEtermUsername(enterpriseId, username, userId, etermUsername);
  }

  /**
   * 禁用用户
   */
  @PostMapping(value = "/user/disable")
  public JsonResult disableUser(HttpServletRequest request,
                                @RequestParam("id") int userId) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.disableUser(enterpriseId, username, userId);
  }

  /**
   * 禁用用户
   */
  @PostMapping(value = "/user/enable")
  public JsonResult enableUser(HttpServletRequest request,
                               @RequestParam("id") int userId) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return userService.enableUser(enterpriseId, username, userId);
  }

  /**
   * 修改用户资料
   *
   * @param syncWxWork 1-同步企业微信,0-不同步
   */
  @PostMapping(value = "/user")
  public JsonResult createUser(HttpServletRequest request,
                               @RequestParam(value = "id", defaultValue = "0") int id,
                               @RequestParam("username") String username,
                               @RequestParam(value = "fullName", defaultValue = "") String empname,
                               @RequestParam(value = "email", defaultValue = "") String email,
                               @RequestParam(value = "mobileNo", defaultValue = "") String mobileNo,
                               @RequestParam(value = "position", defaultValue = "") String position,
                               @RequestParam(value = "etermUsername", defaultValue = "") String etermUsername,
                               @RequestParam(value = "status", defaultValue = "1") final int status,
                               @RequestParam(value = "syncWxWork", defaultValue = "1") final int syncWxWork,
                               @RequestParam(value = "departments[]", required = false) Integer[] deptIds) {
    if (username.length() == 0) {
      return JsonResult.createJsonResult(-1, "用户名必需填写");
    }

    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    JsonResult jsonResult = new JsonResult();
    jsonResult.setStatus("ER");
    jsonResult.setErrcode(-1);

    if (deptIds == null) {
      deptIds = new Integer[1];
      deptIds[0] = 0;
    }

    int retCode;
    if (id == 0) {
      //create user
      User user = new User();
      user.setUsername(username);
      user.setEmpname(empname);
      user.setEmail(email);
      user.setMobileNo(mobileNo);
      user.setPosition(position);
      user.setMd5Password(VerifyCodeUtil.MD5(User.DEFAULT_PASSWORD));
      user.setEtermUsername(etermUsername);
      user.setStatus(status);

      for (int deptId : deptIds) {
        EntDepartment department = enterpriseService.getEntDepartmentById(enterpriseId, deptId);
        user.getDepartments().add(department);
      }

      if (userId == enterpriseId) {
        retCode = userService.createUser(user, enterpriseId, null);
      } else {
        retCode = userService.createUserByRoleAdmin(user, enterpriseId, null);
      }
    } else {
      //update user
      retCode = userService
              .updateUser(enterpriseId, id, empname, email, mobileNo, etermUsername, position, deptIds,
                      status);
    }

    if (retCode > 0) {
      jsonResult.setErrcode(0);
      jsonResult.setStatus("OK");
      jsonResult.setReturnCode(retCode);

      if (syncWxWork == 1) {
        //同步企业微信账号
        enterpriseService
                .createOrUpdateWwUser(enterpriseId, username, empname, email, mobileNo, etermUsername,
                        position);
      }
    } else {
      jsonResult.setErrmsg("失败: " + retCode);
    }

    return jsonResult;
  }

  /**
   * 查找会员信息
   */
  @RequestMapping("/members")
  public CommonDto<UserDto> searchMembers(HttpServletRequest request,
                                          @ModelAttribute("sc") SearchUserCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    List<UserDto> users = userService.searchMembers(enterpriseId, sc);

    CommonDto<UserDto> commonDto = new CommonDto<>();
    commonDto.setDataList(users);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  /**
   * 查找会员信息
   */
  @GetMapping("/member/{id}")
  public UserDto searchMemberDetail(HttpServletRequest request,
                                    @PathVariable("id") final int id) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.searchMemberDetail(enterpriseId, id);
  }

  /**
   * 将会员信息和微信公众号用户解绑
   */
  @PostMapping("/member/{id}/unbindWeixinUser")
  public JsonResult unbindWeixinUser(HttpServletRequest request,
                                     @PathVariable("id") final int id,
                                     @RequestParam("openId") final String openId
  ) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.unbindWeixinUser(enterpriseId, id, openId);
  }

  /**
   * 将会员信息和微信公众号用户 绑定
   */
  @PostMapping("/member/{id}/bindWeixinUser")
  public JsonResult bindWeixinUser(HttpServletRequest request,
                                   @PathVariable("id") final int id,
                                   @RequestParam("openId") final String openId
  ) {
    final int enterpriseId = getEnterpriseId(request);

    return userService.bindWeixinUser(enterpriseId, id, openId);
  }

  @RequestMapping("/enterprise/{id}")
  public Enterprise searchEnterpriseById(HttpServletRequest request,
                                         @PathVariable("id") int id) {
    final int enterpriseId = getEnterpriseId(request);
    Enterprise enterprise = enterpriseService.getEnterpriseById(id);

    return enterprise.getParentEnterprise() == enterpriseId ? enterprise : null;
  }

  /**
   * 查找企业id对应的客户资料
   */
  @RequestMapping("/enterprise/{id}/customer")
  public List<CustomerDetailDto> searchCustomerByEnterpriseId(HttpServletRequest request,
                                                              @PathVariable("id") int id) {
    final int enterpriseId = getEnterpriseId(request);
    Enterprise enterprise = enterpriseService.getEnterpriseById(id);

    if (enterprise.getParentEnterprise() != enterpriseId) {
      return new ArrayList<>();
    }

    return userService.searchCustomerByCustomerEnterpriseId(enterpriseId, id);

  }


  @PostMapping(value = "/deleteWwUser")
  public JsonResult deleteWwUser(HttpServletRequest request,
                                 @RequestParam(value = "id") int id,
                                 @RequestParam("remark") String remark) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.deleteWwUser(enterpriseId, id, remark);
  }

  @PostMapping(value = "/syncWwUser")
  public JsonResult syncWwUser(HttpServletRequest request,
                               @RequestParam(value = "id") int id) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.syncWwUser(enterpriseId, id);
  }

  @RequestMapping("/groups")
  public CommonDto<GroupDto> searchGroups(HttpServletRequest request,
                                          @ModelAttribute("sc") CommonSearchCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    CommonDto<GroupDto> commonDto = new CommonDto<>();

    List<GroupDto> groups = enterpriseService.searchGroups(enterpriseId, sc);

    commonDto.setDataList(groups);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  @PostMapping(value = "/group")
  public JsonResult saveGroup(HttpServletRequest request,
                              @RequestParam("groupName") String groupName
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return enterpriseService.createGroup(enterpriseId, userId, groupName);
  }

  /**
   * 修改组的角色
   */
  @PostMapping(value = "/group/role")
  public JsonResult updateGroupRole(HttpServletRequest request,
                                    @RequestParam("id") int id,
                                    @RequestParam("roleName") String roleName) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return enterpriseService.updateGroupRole(enterpriseId, userId, id, roleName);
  }

  /**
   * 增加组-用户关系
   */
  @PostMapping(value = "/group/user")
  public JsonResult addUserToGroup(HttpServletRequest request,
                                   @RequestParam("userId") int paramUserId,
                                   @RequestParam("groupId") int groupId) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return enterpriseService.addUserToGroup(enterpriseId, userId, paramUserId, groupId);
  }

  /**
   * 删除组-用户关系
   */
  @PostMapping(value = "/group/user/delete")
  public JsonResult deleteUserFromGroup(HttpServletRequest request,
                                        @RequestParam("userId") int paramUserId,
                                        @RequestParam("groupId") int groupId) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return enterpriseService.deleteUserFromGroup(enterpriseId, userId, paramUserId, groupId);
  }


  @RequestMapping("/roles")
  public List<RoleInfo> searchRoles(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.searchRoles(enterpriseId);
  }

  @RequestMapping("/privileges")
  public List<SysPrivilege> searchPrivileges(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.searchPrivileges(enterpriseId);
  }

  /**
   * 查找角色对应的权限
   */
  @RequestMapping("/role/privileges")
  public CommonDto<RolePrivilege> searchRolePrivileges(HttpServletRequest request,
                                                       @ModelAttribute("sc") CommonSearchCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);
    return enterpriseService.searchRolePrivileges(enterpriseId, sc);
  }

  /**
   * 删除角色对应的权限
   */
  @RequestMapping("/role/privilege/{id}/delete")
  public JsonResult deleteRolePrivilege(HttpServletRequest request,
                                        @PathVariable("id") int id) {
    final int enterpriseId = getEnterpriseId(request);
    return enterpriseService.deleteRolePrivilege(enterpriseId, id);
  }

  /**
   * 增加角色对应的权限
   */
  @RequestMapping("/role/add/privilege")
  public JsonResult addRolePrivilege(HttpServletRequest request,
                                     @RequestParam("role") String role,
                                     @RequestParam("privilegeIds[]") Integer[] privilegeIds) {
    final int enterpriseId = getEnterpriseId(request);
    return enterpriseService.addRolePrivilege(enterpriseId, role, privilegeIds);
  }


  /**
   * 查找需要模拟票号的
   */
  @RequestMapping("/fakedTickets")
  public CommonDto<FakeTicketNo> searchFakedTickets(HttpServletRequest request,
                                                    @ModelAttribute("sc") CommonSearchCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);
    return enterpriseService.searchFakedTickets(enterpriseId, sc);
  }

  /**
   * 创建需要模拟票号的航司记录
   */
  @RequestMapping("/fakedTicket/create")
  public JsonResult searchFakedTickets(HttpServletRequest request,
                                       @RequestParam("twoCode") String twoCode) {
    final int enterpriseId = getEnterpriseId(request);
    return enterpriseService.createFakedTicket(enterpriseId, twoCode);
  }


  /**
   * 查找部门
   */
  @RequestMapping("/ent/departments")
  public CommonDto<EntDepartment> searchEntDepartments(HttpServletRequest request,
                                                       @ModelAttribute("sc") CommonSearchCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.searchEntDepartments(enterpriseId, sc);
  }

  /**
   * 同步部门
   */
  @RequestMapping("/ent/departments/sync")
  public JsonResult syncEntDepartments(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.syncEntDepartments(enterpriseId);
  }

  /**
   * 同步企业微信的用户到本地
   */
  @RequestMapping("/ent/department/{id}/users")
  public JsonResult syncDeptUsers(HttpServletRequest request,
                                  @PathVariable("id") int id) {
    final int enterpriseId = getEnterpriseId(request);

    return enterpriseService.syncWwDeptUsers(enterpriseId, id);
  }

  /**
   * 创建部门
   *
   * @param wwDeptId 企业微信部门id
   */
  @RequestMapping(value = "/createDept")
  public JsonResult createDepartment(HttpServletRequest request,
                                     @RequestParam(value = "id", defaultValue = "0") int id,
                                     @RequestParam(value = "wwDeptId", defaultValue = "0") int wwDeptId,
                                     @RequestParam("name") String name,
                                     @RequestParam(value = "role", required = false) String role,
                                     @RequestParam("parentId") int parentId,
                                     @RequestParam("remark") String remark) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return enterpriseService
            .createDepartment(enterpriseId, username, id, name, role, parentId, wwDeptId, remark);
  }

  /**
   * 删除部门
   */
  @RequestMapping(value = "/deleteDept")
  public JsonResult createDepartment(HttpServletRequest request,
                                     @RequestParam(value = "id") int id) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return enterpriseService.deleteDepartment(enterpriseId, username, id);
  }

  /**
   * 下载乘机人资料
   * @param customerId 客户的id(-1: 下载所有客户；0：下载散客的；其它自然数：下载客户id所对应公司的乘机人资料
   * @param fileFormat 0-csv, 1-excel
   */
  @RequestMapping("/passengers/download")
  public void downloadPassengers(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "customerId", defaultValue = "-1") final int customerId,
                                 @RequestParam(value = "fileFormat", defaultValue = "0") final int fileFormat) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    if (fileFormat == 0) {
      downloadPassengersCsv(response, enterpriseId, userId, customerId);
    } else {
      downloadPassengersExcel(response, enterpriseId, userId, customerId);
    }
  }


  private void downloadPassengersCsv(HttpServletResponse response, final int enterpriseId, final int userId,
                                     final int customerId) {
    SearchCustomerCriteria sc = new SearchCustomerCriteria();

    //输出
    PrintWriter out;
    try {
      String filename =
              "passengers-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss")
                      + ".csv";

      out = generatePrintWriter(filename, response);

      StringBuilder sb = BillUtil.exportPassengerTitle();
      out.print(sb);
      out.flush();

      sc.setPageNo(1);
      sc.setPageSize(500);
      sc.setCustomerId(customerId);

      boolean b = true;
      while (b) {
        b = false;

        List<PassengerDto> passengers = enterpriseService.searchPsgInfo(enterpriseId, userId, sc);

        for (PassengerDto dto : passengers) {
          if (dto == null) {
            continue;
          }
          sb = BillUtil.exportPassengerContent(dto);
          out.print(sb);
        }
        out.flush();

        if (sc.getPageNo() < sc.getPage().getPageTotal()) {
          b = true;
          sc.setPageNo(sc.getPageNo() + 1);
        }
      }

      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void downloadPassengersExcel(HttpServletResponse response, final int enterpriseId, final int userId,
                                       final int customerId) {
    SearchCustomerCriteria sc = new SearchCustomerCriteria();

    final String TEMPLATE_PATH = "/templates/passengers-download.xls";

    final String templatePath = Objects.requireNonNull(
            Thread.currentThread().getContextClassLoader().getResource(TEMPLATE_PATH))
            .getPath();
    Workbook workbook = ExcelUtils.readExcel(templatePath);
    Sheet sheet = workbook.getSheetAt(0);
    try {
      String filename = "passengers-" + DateUtil.formatDate(DateUtil.getCurDateTime(), "yyyyMMddHHmmss")
              + ".xls";
      OutputStream out = response.getOutputStream();
      response.setContentType("application/ms-excel;charset=UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename="
              .concat(String.valueOf(URLEncoder.encode(filename, StandardCharsets.UTF_8))));
      out.flush();

      sc.setPageNo(1);
      sc.setPageSize(5000);
      sc.setCustomerId(customerId);

      //数据行从第二行开始（行从0开始计数）
      int curDataRow = 0;

      boolean b = true;
      while (b) {
        b = false;

        List<PassengerDto> passengers = enterpriseService.searchPsgInfo(enterpriseId, userId, sc);

        for (PassengerDto dto : passengers) {
          if (dto == null) {
            continue;
          }

          curDataRow++;
          while (sheet.getLastRowNum() < curDataRow) {
            sheet.createRow(sheet.getLastRowNum() + 1);
          }
          Row row = sheet.getRow(curDataRow);
          row.createCell(0).setCellValue(dto.getNameEn());
          row.createCell(1).setCellValue(dto.getNameCn());
          //性别
          String gender = "";
          if (dto.getGender() != null) {
            if (dto.getGender() == 1) {
              gender = "男";
            } else if (dto.getGender() == 2) {
              gender = "女";
            }
          }
          row.createCell(2).setCellValue(gender);

          String mobile = dto.getMobile() == null ? "" : dto.getMobile();
          row.createCell(3).setCellValue(mobile);

          String phone = dto.getPhone() == null ? "" : dto.getPhone();
          row.createCell(4).setCellValue(phone);

          String email = dto.getEmail() == null ? "" : dto.getEmail();
          row.createCell(5).setCellValue(email);

          row.createCell(6).setCellValue(dto.getBirthday());

          row.createCell(7).setCellValue(dto.getIdNo());

          row.createCell(8).setCellValue(dto.getPassportNo());

          row.createCell(9).setCellValue(dto.getPassportExpiry());

          row.createCell(10).setCellValue(dto.getNationality());

          String customerName = dto.getCustomer() == null ? "" : dto.getCustomer().getName();
          row.createCell(11).setCellValue(customerName);

          String createTime = dto.getCreateTime() == null ? "" : DateUtil.formatDate(dto.getCreateTime(), "yyyy-MM-dd");
          row.createCell(12).setCellValue(createTime);

          row.createCell(13).setCellValue(DateUtil.formatDate(dto.getRecency()));
          var cell = row.createCell(14);
              cell.setCellValue(dto.getLatestBuyCount());

        }


        if (sc.getPageNo() < sc.getPage().getPageTotal()) {
          b = true;
          sc.setPageNo(sc.getPageNo() + 1);
        }
      }

      workbook.write(out);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  /**
   * 查找旅行代码
   */
  @RequestMapping(value = "/tourCodes")
  public List<PnrTourCode> searchTourCodes(HttpServletRequest request) {
    return enterpriseService.searchTourCodes(getEnterpriseId(request));
  }

  /**
   * 修改或者新建旅行代码
   */
  @PostMapping(value = "/tourCode")
  public JsonResult createTourCode(HttpServletRequest request,
                                   @RequestParam("id") int id,
                                   @RequestParam("carrier") String carrier,
                                   @RequestParam("tourCode") String tourCode,
                                   @RequestParam("patCode") String patCode,
                                   @RequestParam("status") int status,
                                   @RequestParam("ticketType") int ticketType,
                                   @RequestParam("dpayPassword") String dpayPassword,
                                   @RequestParam("dpayAmount") int dpayAmount,
                                   @RequestParam("minDpayAmount") int minDpayAmount
  ) {
    PnrTourCode pnrTourCode = new PnrTourCode();
    pnrTourCode.setId(id);
    pnrTourCode.setCarrier(carrier);
    pnrTourCode.setTourCode(tourCode);
    pnrTourCode.setPatCode(patCode);
    pnrTourCode.setStatus(status);
    pnrTourCode.setDpayPassword(dpayPassword);
    pnrTourCode.setDpayAmount(dpayAmount);
    pnrTourCode.setMinDpayAmount(minDpayAmount);
    pnrTourCode.setTicketType(ticketType);

    return enterpriseService
            .createOrUpdateTourCode(getEnterpriseId(request), getUsername(request), pnrTourCode);
  }

  /**
   * 查找当前企业的eterm参数设置
   */
  @GetMapping(value = "/config/eterm")
  public EtermEntConfig searchEnterpriseEtermConfig(HttpServletRequest request) {
    return enterpriseService.searchEtermConfig(getEnterpriseId(request));
  }

  /**
   * 保存当前企业的eterm参数设置
   */
  @PostMapping(value = "/config/eterm")
  public JsonResult updateEnterpriseEtermConfig(HttpServletRequest request,
                                                @RequestParam("host") String host,
                                                @RequestParam("port") int port,
                                                @RequestParam("username") String username,
                                                @RequestParam("password") String password) {
    return enterpriseService
            .saveEtermConfig(getEnterpriseId(request), host, port, username, password);
  }

  /**
   * 当前企业的全局加价
   */
  @GetMapping(value = "/config/markup")
  public MarkupConfigDto searchEnterpriseMarkupConfig(HttpServletRequest request) {
    return enterpriseService.searchMarkupConfig(getEnterpriseId(request));
  }

  /**
   * 修改全局加价
   */
  @PostMapping(value = "/config/markup")
  public JsonResult saveEnterpriseMarkupConfig(HttpServletRequest request,
                                               @RequestParam("hotelMarkup") int hotelMarkup,
                                               @RequestParam("carMarkup") int carMarkup,
                                               @RequestParam("boardingCardMarkup") int boardingCardMarkup,
                                               @RequestParam("domFlightMarkup") int domFlightMarkup,
                                               @RequestParam("intlFlightMarkup") int intlFlightMarkup
  ) {
    return enterpriseService
            .saveMarkupConfig(getEnterpriseId(request), hotelMarkup, carMarkup, boardingCardMarkup, domFlightMarkup, intlFlightMarkup);
  }


  /**
   * 查找当前企业的sms参数设置
   */
  @GetMapping(value = "/config/sms")
  public SmsConfigDto searchEnterpriseSmsConfig(HttpServletRequest request) {
    return enterpriseService.searchSmsConfig(getEnterpriseId(request));
  }

  /**
   * 修改当前企业的sms参数设置
   */
  @PostMapping(value = "/config/sms")
  public JsonResult updateEnterpriseSmsConfig(HttpServletRequest request,
                                              @RequestParam("companySign") String companySign,
                                              @RequestParam("url") String url,
                                              @RequestParam("accessKey") String accessKey,
                                              @RequestParam(value = "secretKey", required = false) String secretKey) {
    return enterpriseService.updateSmsConfig(getEnterpriseId(request), getUsername(request), companySign, url, accessKey, secretKey);
  }

  /**
   * 查找当前企业的vaas参数设置
   */
  @GetMapping(value = "/config/vaas")
  public VaasConfigDto searchEnterpriseVaasConfig(HttpServletRequest request) {
    VaasConfigDto dto = enterpriseService.searchVaasConfig(getEnterpriseId(request));

    dto.setSecretKey(null);

    return dto;
  }

  /**
   * 修改当前企业的vaas参数设置
   */
  @PostMapping(value = "/config/vaas")
  public JsonResult updateEnterpriseVaasConfig(HttpServletRequest request,
                                               @RequestParam("url") String url,
                                               @RequestParam("username") String username,
                                               @RequestParam(value = "secretKey", required = false) String secretKey) {
    return enterpriseService.updateVaasConfig(getEnterpriseId(request), getUsername(request), url, username, secretKey);
  }

  /**
   * 查找当前企业的order参数设置
   */
  @GetMapping(value = "/config/order")
  public OrderConfigDto searchOrderConfig(HttpServletRequest request) {
    return enterpriseService.searchOrderConfig(getEnterpriseId(request));
  }

  /**
   * 修改当前企业的订单参数设置
   */
  @PostMapping(value = "/config/order")
  public JsonResult updateOrderConfig(HttpServletRequest request,
                                      @RequestParam("oneStepCreate") int oneStepCreate,
                                      @RequestParam("hideCustomerName") int hideCustomerName,
                                      @RequestParam("onlySeeOwn") int onlySeeOwn,
                                      @RequestParam(value = "autoTicketMode", defaultValue = "0") int autoTicketMode,
                                      @RequestParam(value = "autoTicketSwitch", defaultValue = "0") int autoTicketSwitch,
                                      @RequestParam(value = "validationMode", defaultValue = "0") int validationMode) {
    try {
      var configDto = new OrderConfigDto();
      configDto.setOneStepCreateOrder(oneStepCreate);
      configDto.setHideCustomerName(hideCustomerName);
      configDto.setIsOnlySeeOwn(onlySeeOwn);
      configDto.setAutoTicketMode(autoTicketMode);
      configDto.setAutoTicketSwitch(autoTicketSwitch);
      configDto.setValidationMode(validationMode);

      return enterpriseService.updateOrderConfig(getEnterpriseId(request), getUsername(request), configDto);
    } catch (Exception ex) {
      return JsonResult.createJsonResult(-100, ex.getMessage());
    }
  }

  /**
   * 查找当前企业的微信公众号开发参数
   */
  @GetMapping(value = "/config/weixin-service")
  public WeixinServiceConfig searchWeixinServiceConfig(HttpServletRequest request) {
    return enterpriseService.searchWeixinServiceConfig(getEnterpriseId(request));
  }

  /**
   * 修改当前企业的微信公众号开发参数
   */
  @PostMapping(value = "/config/weixin-service")
  public JsonResult updateWeixinServiceConfig(HttpServletRequest request,
                                              @RequestParam("appId") String appId,
                                              @RequestParam("appSecret") String appSecret,
                                              @RequestParam("token") String token,
                                              @RequestParam("encodingKey") String encodingKey) {
    return enterpriseService.updateWeixinServiceConfig(getEnterpriseId(request), getUsername(request),
            appId, appSecret, token, encodingKey);
  }


  /**
   * 查找当前企业的企业微信开发参数
   */
  @GetMapping(value = "/config/work-weixin")
  public List<WeixinEntConfig> searchWorkWeixinConfig(HttpServletRequest request) {
    return enterpriseService.searchWorkWeixinConfig(getEnterpriseId(request));
  }

  /**
   * 修改企业微信开发参数
   */
  @PostMapping(value = "/config/work-weixin")
  public JsonResult updateWorkWeixinConfig(HttpServletRequest request,
                                           @RequestParam("corpId") String corpId,
                                           @RequestParam("msgType") int msgType,
                                           @RequestParam("agentId") int agentId,
                                           @RequestParam("agentSecret") String agentSecret,
                                           @RequestParam("token") String token,
                                           @RequestParam("encodingKey") String encodingKey) {
    return enterpriseService.updateWorkWeixinConfig(getEnterpriseId(request), getUsername(request),
            corpId, msgType, agentId, agentSecret, token, encodingKey);
  }


  /**
   * 查找当前企业的支付宝开发参数
   */
  @GetMapping(value = "/config/alipay")
  public List<EntAlipayCfgDto> searchAlipayConfigs(HttpServletRequest request) {
    return enterpriseService.searchAlipayConfigs(getEnterpriseId(request));
  }

  /**
   * 修改企业支付宝开发参数
   */
  @PostMapping(value = "/config/alipay")
  public JsonResult updateAlipayConfig(HttpServletRequest request,
                                           @RequestParam("mainAccount") String mainAccount,
                                           @RequestParam("appId") String appId,
                                           @RequestParam("privateKey") String privateKey,
                                           @RequestParam("alipayPublicKey") String alipayPublicKey,
                                           @RequestParam("returnUrl") String returnUrl,
                                           @RequestParam("notifyUrl") String notifyUrl) {
    return enterpriseService.updateAlipayConfig(getEnterpriseId(request), getUsername(request),
            mainAccount, appId, privateKey, alipayPublicKey, returnUrl, notifyUrl);
  }

  /**
   * 删除企业支付宝开发参数
   */
  @DeleteMapping(value = "/config/alipay/{id}")
  public JsonResult deleteAlipayConfig(HttpServletRequest request,
                                       @PathVariable("id") int id) {
    return enterpriseService.deleteAlipayConfig(getEnterpriseId(request), getUsername(request), id);
  }

  /**
   * 获取租户的系统参数
   */
  @GetMapping(value = "/configs")
  public EnterpriseConfigDto searchEntConfig(HttpServletRequest request) {
    return enterpriseService.searchEntConfig(getEnterpriseId(request));
  }

  /**
   * 修改卖家设置
   */
  @PostMapping(value = "/configs")
  public JsonResult updateSellerConfig(HttpServletRequest request,
                                       @RequestParam("workDay") String workDay,
                                       @RequestParam("workBeginTime") String workBeginTime,
                                       @RequestParam("workEndTime") String workEndTime,
                                       @RequestParam("receivingAccount") String receivingAccount,
                                       @RequestParam(value = "defaultBottomPrice", defaultValue = "100") int defaultBottomPrice,
                                       @RequestParam(value = "priceAdjustment", defaultValue = "25") int priceAdjustment,
                                       @RequestParam(value = "crazyAirlines", required = false) String crazyAirlines,
                                       @RequestParam(value = "tbookingMaxLoss", defaultValue = "-1") float tbookingMaxLoss,
                                       @RequestParam(value = "bspPrinterNo", defaultValue = "1") int bspPrinterNo) {
    final int enterpriseId = getEnterpriseId(request);

    enterpriseService.updateEntConfig(enterpriseId, EnterpriseConfig.ENTERPRISE_DEFAULT_BOTTOM_PRICE, defaultBottomPrice + "");
    enterpriseService.updateEntConfig(enterpriseId, EnterpriseConfig.ENTERPRISE_PRICE_ADJUSTMENT, priceAdjustment + "");
    enterpriseService.updateEntConfig(enterpriseId, EnterpriseConfig.ENTERPRISE_AIRLINE_IN_CRAZY_MODE, crazyAirlines);
    enterpriseService.updateEntConfig(enterpriseId, EnterpriseConfig.ENTERPRISE_TBOOKING_MAX_LOSS, tbookingMaxLoss + "");
    enterpriseService.updateEntConfig(enterpriseId, EnterpriseConfig.ENTERPRISE_BSP_PRINTER, bspPrinterNo + "");

    return enterpriseService.updateWorkTime(enterpriseId, workDay, workBeginTime, workEndTime, receivingAccount);
  }

  @RequestMapping(value = "/dataFields")
  public List<DataFieldInfo> searchDataFields() {
    return enterpriseService.searchDataFields();
  }

  @PostMapping(value = "/dataTemplate", consumes = "application/json")
  public JsonResult createDataTemplate(HttpServletRequest request,
                                       @RequestBody DataTemplateDto dto) {
    return enterpriseService.createDataTemplate(getEnterpriseId(request), dto);
  }

  @PostMapping(value = "/dataTemplate/{id}/delete")
  public JsonResult deleteDataTemplate(HttpServletRequest request,
                                       @PathVariable("id") int id) {
    return enterpriseService.deleteDataTemplateById(getEnterpriseId(request), id);
  }

  @PostMapping(value = "/api-product-supplier")
  public JsonResult saveApiProductSupplier(HttpServletRequest request,
                                           @RequestParam("productType") int productType,
                                           @RequestParam("supplierId") int supplierId) {
    return enterpriseService.saveApiProductSupplier(getEnterpriseId(request), productType, supplierId);
  }

  @DeleteMapping(value = "/api-product-supplier/{id}")
  public JsonResult deleteApiProductSupplier(HttpServletRequest request,
                                             @PathVariable("id") int id) {
    return enterpriseService.deleteApiProductSupplier(getEnterpriseId(request), id);
  }

  @GetMapping(value = "/api-product-suppliers")
  public List<ProductDefaultSupplier> searchApiProductSupplier(HttpServletRequest request) {
    return enterpriseService.searchApiProductSupplier(getEnterpriseId(request));
  }


  /**
   * 查找 客服服务分组
   */
  @RequestMapping(value = "/customerServiceGroups")
  public CommonDto<GroupCustomerService> searchCustomerServiceGroups(HttpServletRequest request) {
    List<GroupCustomerService> list = enterpriseService.searchCustomerServiceGroups(getEnterpriseId(request));

    CommonDto<GroupCustomerService> commonDto = new CommonDto<>();
    commonDto.setDataList(list);

    return commonDto;
  }

  /**
   * 修改或者新建 客服服务分组
   */
  @PostMapping(value = "/customerServiceGroup")
  public JsonResult createCustomerServiceGroup(HttpServletRequest request,
                                               @RequestParam("id") int id,
                                               @RequestParam("code") String code,
                                               @RequestParam("name") String name
  ) {

    return enterpriseService
            .createOrUpdateCustomerServiceGroup(getEnterpriseId(request), getUsername(request), id, code, name);
  }


  /**
   * 将客户分组, 保存客户的分组信息
   */
  @PostMapping(value = "/customerGroup")
  public JsonResult updateCustomerGroup(HttpServletRequest request,
                                        @RequestParam("customerId") int customerId,
                                        @RequestParam("groupId") int groupId
  ) {

    return enterpriseService
            .updateCustomerGroup(getEnterpriseId(request), getUsername(request), customerId, groupId);
  }


  /**
   * 移除客户分组
   */
  @PostMapping(value = "/removeCustomerGroup")
  public JsonResult deleteCustomerGroup(HttpServletRequest request,
                                        @RequestParam("customerId") int customerId
  ) {
    return enterpriseService
            .deleteCustomerGroup(getEnterpriseId(request), getUsername(request), customerId);
  }


  /**
   * 将客服代表分组, 保存客服代表的分组信息
   */
  @PostMapping(value = "/representativeGroup")
  public JsonResult updateRepresentativeGroup(HttpServletRequest request,
                                              @RequestParam("userId") int userId,
                                              @RequestParam("groupId") int groupId
  ) {

    return enterpriseService
            .updateRepresentativeGroup(getEnterpriseId(request), getUsername(request), userId, groupId);
  }


  /**
   * 移除客服代表分组
   */
  @PostMapping(value = "/removeRepresentativeGroup")
  public JsonResult deleteRepresentativeGroup(HttpServletRequest request,
                                              @RequestParam("userId") int userId
  ) {
    return enterpriseService
            .deleteRepresentativeGroup(getEnterpriseId(request), getUsername(request), userId);
  }

  /**
   * 查找客户服务收费模板
   */
  @GetMapping(value = "/customerServiceTemplates")
  public CommonDto<CustomerServiceTemplateDto> searchCustomerServiceTemplates(HttpServletRequest request) {
    List<CustomerServiceTemplateDto> list = enterpriseService.searchCustomerServiceTemplates(getEnterpriseId(request));

    CommonDto<CustomerServiceTemplateDto> commonDto = new CommonDto<>();
    commonDto.setDataList(list);

    return commonDto;
  }

  /**
   * 修改或者新建 客户服务收费模板
   */
  @PostMapping(value = "/customerServiceTemplate")
  public JsonResult createCustomerServiceTemplate(HttpServletRequest request,
                                                  @RequestParam("id") int id,
                                                  @RequestParam("code") String code,
                                                  @RequestParam("name") String name,
                                                  @RequestParam("flightPriceMode") int flightPriceMode,
                                                  @RequestParam("flightTicketingFee") int flightTicketingFee,
                                                  @RequestParam("flightInsurance") int flightInsurance,
                                                  @RequestParam("flightRefundFee") int flightRefundFee,
                                                  @RequestParam("flightChangeFee") int flightChangeFee,
                                                  @RequestParam("reportShowFee") int reportShowFee,
                                                  @RequestParam("gpMode") int gpMode,
                                                  @RequestParam(name = "strength", defaultValue = "0") int strength
  ) {
    final int enterpriseId = getEnterpriseId(request);
    CustomerServiceTemplate tpl = new CustomerServiceTemplate();
    tpl.setId(id);
    tpl.setEnterpriseId(enterpriseId);
    tpl.setTemplateCode(code);
    tpl.setTemplateName(name);
    tpl.setFlightPriceMode(flightPriceMode);
    tpl.setFlightTicketingFee(flightTicketingFee);
    tpl.setFlightInsurance(flightInsurance);
    tpl.setFlightRefundFee(flightRefundFee);
    tpl.setFlightChangeFee(flightChangeFee);
    tpl.setReportShowFee(reportShowFee);
    tpl.setGpMode(gpMode);
    tpl.setStrength(strength);
    return enterpriseService
            .createOrUpdateCustomerServiceTemplate(enterpriseId, getUsername(request), tpl);
  }

  /**
   * 修改或者新建 客户服务收费模板的机票特定规则
   */
  @PostMapping(value = "/customerServiceTemplate/{id}/flightRule")
  public JsonResult createOrUpdateCustomerServiceFlightRule(HttpServletRequest request,
                                                            @PathVariable("id") int id,
                                                            @RequestParam("carrier") String carrier,
                                                            @RequestParam("subclasses") String subclasses,
                                                            @RequestParam("flightTicketingFee") int flightTicketingFee,
                                                            @RequestParam("flightRefundFee") int flightRefundFee,
                                                            @RequestParam("flightChangeFee") int flightChangeFee
  ) {
    final int enterpriseId = getEnterpriseId(request);
    CustomerServiceFlightRule fltRule = new CustomerServiceFlightRule();
    fltRule.setCarrier(carrier);
    fltRule.setSubclasses(subclasses);
    fltRule.setFlightTicketingFee(flightTicketingFee);
    fltRule.setFlightRefundFee(flightRefundFee);
    fltRule.setFlightChangeFee(flightChangeFee);
    return enterpriseService
            .createOrUpdateCustomerServiceFlightRule(enterpriseId, getUsername(request), id, fltRule);
  }

  /**
   * 获取客户服务收费模板
   */
  @GetMapping(value = "/customerServiceTemplate/{id}")
  public CustomerServiceTemplateDto getCustomerServiceTemplate(HttpServletRequest request,
                                                               @PathVariable("id") int id
  ) {
    return enterpriseService
            .getCustomerServiceTemplateById(getEnterpriseId(request), getUsername(request), id);
  }

  /**
   * 为客户设置客服模板
   */
  @PostMapping("/customerTemplate")
  public JsonResult updateCustomerTemplate(HttpServletRequest request,
                                           @RequestParam("customerId") int customerId,
                                           @RequestParam(value = "templateId", defaultValue = "0") int templateId,
                                           @RequestParam(value = "templateCode", defaultValue = "") String templateCode
  ) {
    return enterpriseService
            .updateCustomerTemplate(getEnterpriseId(request), getUsername(request), customerId, templateId, templateCode);
  }

  /**
   * 查找报表模板
   */
  @GetMapping(value = "/reportTemplates")
  public CommonDto<ReportTemplateInfo> searchReportTemplates(HttpServletRequest request) {
    List<ReportTemplateInfo> list = enterpriseService.searchReportTemplates(getEnterpriseId(request));

    CommonDto<ReportTemplateInfo> commonDto = new CommonDto<>();
    commonDto.setDataList(list);

    return commonDto;
  }

  /**
   * 为客户设置报表模板
   */
  @PostMapping(value = "/customer/{customerId}/reportTemplate")
  public JsonResult updateCustomerReportTemplate(HttpServletRequest request,
                                                 @PathVariable("customerId") int customerId,
                                                 @RequestParam("templateId") int templateId
  ) {
    return enterpriseService
            .updateCustomerReportTemplate(getEnterpriseId(request), getUsername(request), customerId, templateId);
  }

}
